import React from 'react';
import {VisibilityFilters} from '../../store/action-types'
import classNames from 'classnames';
import './index.css'

const {SHOW_ALL, SHOW_COMPLETED, SHOW_UNCOMPLETED} = VisibilityFilters;

class Footer extends React.Component {
    constructor(props) {
        super(props);
        this.onHashChange = this.onHashChange.bind(this);
        this.handleClearCompleted = this.handleClearCompleted.bind(this)
    }

    componentDidMount() {
        window.addEventListener('hashchange', this.onHashChange)
        this.onHashChange()
    }

    itemsOrItem(count) {
        return count !== 1 ? 'items' : 'item'
    }

    onHashChange() {
        let visibility = window.location.hash.replace(/#\/?/, '')
        let filter;
        switch (visibility) {
            case 'all':
                filter = SHOW_ALL;
                break;
            case 'active':
                filter = SHOW_UNCOMPLETED;
                break;
            case 'completed':
                filter = SHOW_COMPLETED;
                break;
            default:
                filter = SHOW_ALL;
        }
        this.props.onChangeVisibilityFilter(filter)
    }

    componentWillUnmount() {
        window.removeEventListener('hashchange', this.onHashChange)
    }

    handleClearCompleted() {
        this.props.onClearCompletedTodo()
    }

    render() {
        let count = this.props.activeItems;
        let filter = this.props.filter;
        return (
            <footer className='footer'>
                <span className='todo-count'><strong>{count}</strong> {this.itemsOrItem(count)} left</span>
                <ul className='filters'>
                    <li>
                        <a href='#/all' className={classNames({selected: SHOW_ALL === filter})}>ALL</a>
                    </li>
                    <li>
                        <a href='#/active' className={classNames({selected: SHOW_UNCOMPLETED === filter})}>Active</a>
                    </li>
                    <li>
                        <a href='#/completed'
                           className={classNames({selected: SHOW_COMPLETED === filter})}>Completed</a>
                    </li>
                </ul>
                {this.props.completedItems > 0 &&
                <button className='clear-completed'
                        onClick={this.handleClearCompleted}>Clear completed</button>
                }
            </footer>
        )
    }
}

export default Footer